package com.yuyang.wifi.activitys.mine;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AppOpsManager;
import android.app.Notification;
import android.app.WallpaperManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yuyang.wifi.R;
import com.yuyang.wifi.activitys.NewMainHomeActivity;
import com.yuyang.wifi.base.BaseActivity;
import com.yuyang.wifi.base.BaseResult;
import com.yuyang.wifi.dialog.AddMainScreenDialog;
import com.yuyang.wifi.dialog.BaseDialogFragment;
import com.yuyang.wifi.service.LiveWallpaperService;
import com.yuyang.wifi.utils.DeviceUtil;
import com.yuyang.wifi.utils.GetIPAdsUtil;
import com.yuyang.wifi.utils.GetMacAdsUtil;
import com.yuyang.wifi.utils.RxUtil;
import com.yuyang.wifi.utils.Skip;
import com.yuyang.wifi.utils.ToastUtils;
import com.yuyang.wifi.utils.network.BaseDataSubscriber;
import com.yuyang.wifi.utils.network.HttpErrorHandler;
import com.yuyang.wifi.utils.network.HttpManager;
import com.yuyang.wifi.utils.network.RxDataInstance;
import com.yuyang.wifi.views.LoadCsjMsgUtils;

import org.w3c.dom.Text;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import butterknife.BindView;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class WarningActivity extends BaseActivity {

    @BindView(R.id.tv_wifi_safe)
    TextView tvWifiSafe;
    @BindView(R.id.tv_notification)
    TextView tvNotification;
    @BindView(R.id.tv_floating_window)
    TextView tvFloatingWindow;
    @BindView(R.id.tv_charge)
    TextView tvCharge;
    @BindView(R.id.iv_wifi_safe)
    ImageView ivWifiSafe;
    @BindView(R.id.iv_notification)
    ImageView ivNotification;
    @BindView(R.id.iv_floating_warn)
    ImageView ivFloatingWarn;
    @BindView(R.id.tv_restore_hint_text)
    TextView tvRestoreHintText;
    @BindView(R.id.express_container)
    FrameLayout mExpressContainer;
    @BindView(R.id.rl_one_key_restore)
    RelativeLayout rlOneKeyRestore;
    private boolean isFloatOpen = false;
    private boolean isNoticeOpen = false;
    private boolean isPagerOpen = false;
    private boolean isUserOpen = false;
    private List<String> mDataList = new ArrayList<>();
    private final static int REQUEST_CODE_SET_WALLPAPER = 0x001;

    @Override
    protected void initActionBar() {


    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_warning;
    }

    @Override
    protected void initContentView() {
//        int screenWidth = DeviceUtil.getWidth(WarningActivity.this);
//        LoadCsjMsgUtils csjMsgInstance = LoadCsjMsgUtils.getInstance();
//        csjMsgInstance.load(WarningActivity.this, mExpressContainer, screenWidth, 287, "csj_msg_speed_finish");
    }

    @Override
    protected void onResume() {
        super.onResume();
        mDataList.clear();
        checkPermission();
        checkNotify();
        //没有开启权限去申请权限
//        if (!getAccessToUsageRecords(WarningActivity.this)) {
//            setBtnState(tvCharge, R.drawable.bg_green_radius_21, "去修复", R.color.white);
//            isUserOpen = false;
//        } else {
//            setBtnState(tvCharge, R.drawable.bg_grey_radius_21, "已修复", R.color.white);
//            isUserOpen = true;
//            // Toast.makeText(this, "权限已开启！", Toast.LENGTH_SHORT).show();
//        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                boolean pagerServiceRunning = isPagerServiceRunning();
                if (!pagerServiceRunning) {
                    setBtnstates(tvWifiSafe, ivWifiSafe, false);
                    isPagerOpen = false;
                    mDataList.add(2, "0");
                } else {
                    setBtnstates(tvWifiSafe, ivWifiSafe, true);
                    isPagerOpen = true;
                    mDataList.add(2, "1");
                }

                int num = 0;
                for (int i = 0; i < mDataList.size(); i++) {
                    String s = mDataList.get(i);
                    if (s.equals("0")) {
                        num++;
                    }
                }
                if (num == 0) {
                    rlOneKeyRestore.setVisibility(View.GONE);
                } else {
                    rlOneKeyRestore.setVisibility(View.VISIBLE);
                    tvRestoreHintText.setText("一键修复（" + num + "）个问题");
                }
            }
        }, 500);
    }

    private void checkNotify() {
        if (!checkNotifySetting(WarningActivity.this)) {
            setBtnstates(tvNotification, ivNotification, false);
            isNoticeOpen = false;
            mDataList.add(1, "0");
        } else {
            setBtnstates(tvNotification, ivNotification, true);
            isNoticeOpen = true;
            mDataList.add(1, "1");
        }

    }

    private void setBtnstates(TextView tv, ImageView iv, boolean staet) {
        if (staet) {
            tv.setVisibility(View.VISIBLE);
            iv.setVisibility(View.GONE);
        } else {
            tv.setVisibility(View.GONE);
            iv.setVisibility(View.VISIBLE);
        }
    }

    @OnClick({R.id.iv_back, R.id.rl_wifi_safe_layout, R.id.rl_notification_layout,
            R.id.rl_floating_window_layout, R.id.tv_charge, R.id.rl_one_key_restore})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.rl_wifi_safe_layout:
                if (!isPagerOpen) {
                    skipHintClickPage();
                }
                break;
            case R.id.rl_notification_layout://应用通知显示在此设备上
                if (!isNoticeOpen) {
                    goToSet(WarningActivity.this);
                }
                break;
            case R.id.rl_floating_window_layout://在其它应用上层显示
                if (!isFloatOpen) {
                    startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                            Uri.parse("package:" + getPackageName())), 0);
                }
                break;
            case R.id.tv_charge://使用情况访问权限
//                if (!isUserOpen) {
//                    startActivityForResult(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS,
//                            Uri.parse("package:" + getPackageName())), 0);
//                }
                break;
            case R.id.rl_one_key_restore:

                if (!isPagerOpen) {
                    skipHintClickPage();
                    return;
                }

                if (!isNoticeOpen) {
                    goToSet(WarningActivity.this);
                    return;
                }

                if (!isFloatOpen) {
                    startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                            Uri.parse("package:" + getPackageName())), 0);
                }
                break;
        }
    }

    private void skipHintClickPage() {
        Intent intent = new Intent(this, HintClickActivity.class);
        intent.putExtra("mJumpType", "warn");
        startActivity(intent);
    }

    /**
     * 跳转到系统设置壁纸界面
     *
     * @param context
     * @param paramActivity
     */
    public static void setLiveWallpaper(Context context, Activity paramActivity, int requestCode) {
        try {
            Intent localIntent = new Intent();
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {//ICE_CREAM_SANDWICH_MR1  15
                localIntent.setAction(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);//android.service.wallpaper.CHANGE_LIVE_WALLPAPER
                //android.service.wallpaper.extra.LIVE_WALLPAPER_COMPONENT
                localIntent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT
                        , new ComponentName(context.getApplicationContext().getPackageName()
                                , LiveWallpaperService.class.getCanonicalName()));
            } else {
                localIntent.setAction(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER);//android.service.wallpaper.LIVE_WALLPAPER_CHOOSER
            }
            paramActivity.startActivityForResult(localIntent, requestCode);
        } catch (Exception localException) {
            localException.printStackTrace();
        }
    }

    //悬浮窗
    public void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(WarningActivity.this)) {
            setBtnstates(tvFloatingWindow, ivFloatingWarn, false);
            isFloatOpen = false;
            mDataList.add(0, "0");
        } else {
            setBtnstates(tvFloatingWindow, ivFloatingWarn, true);
            isFloatOpen = true;
            mDataList.add(0, "1");
        }
    }

//    public void onActivityResult(Activity activity,
//                                 int requestCode,
//                                 int resultCode,
//                                 Intent data,
//                                 OnWindowPermissionListener onWindowPermissionListener) {
//        if (requestCode == 0) {
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
//                    && !Settings.canDrawOverlays(activity)) {
//                Toast.makeText(activity.getApplicationContext(), "授权失败", Toast.LENGTH_SHORT).show();
//                if (onWindowPermissionListener != null)
//                    onWindowPermissionListener.onFailure();
//            } else {
//                Toast.makeText(activity.getApplicationContext(), "授权成功", Toast.LENGTH_SHORT).show();
//                if (onWindowPermissionListener != null)
//                    onWindowPermissionListener.onSuccess();
//            }
//        }
//    }
//
//    public interface OnWindowPermissionListener {
//        void onSuccess();
//
//        void onFailure();
//    }


    /**
     * 获取通知权限
     */
    public boolean checkNotifySetting(Context context) {
        NotificationManagerCompat manager = NotificationManagerCompat.from(context);
        return manager.areNotificationsEnabled();
    }

    public void goToSet(Context context) {
        try {
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
            //这种方案适用于 API 26, 即8.0（含8.0）以上可以用
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
                intent.putExtra(Notification.EXTRA_CHANNEL_ID, context.getApplicationInfo().uid);
            } else {
                //这种方案适用于 API21——25，即 5.0——7.1 之间的版本可以使用
                intent.putExtra("app_package", context.getPackageName());
                intent.putExtra("app_uid", context.getApplicationInfo().uid);
            }
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                // 出现异常则跳转到应用设置界面：锤子坚果3——OC105 API25
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", context.getPackageName(), null);
                intent.setData(uri);
                context.startActivity(intent);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }


    //返回true表示用户授予了权限，false表示用户没有授予权限
    public boolean getAccessToUsageRecords(Context context) {
        //API > 23  &&  API 小于25版本的监测使用记录访问权限是否授予方式
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M && Build.VERSION.SDK_INT <= Build.VERSION_CODES.N_MR1) {
            int permissionContextCompat = ContextCompat.checkSelfPermission(context, Manifest.permission.PACKAGE_USAGE_STATS);
            return permissionContextCompat == PackageManager.PERMISSION_GRANTED;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
            //API > 25 版本的使用记录访问权限监测方式 适用于 Android 8.0 版本以上
            AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            int mode;
            mode = appOps.checkOpNoThrow("android:get_usage_stats", android.os.Process.myUid(), context.getPackageName());
            return mode == AppOpsManager.MODE_ALLOWED;
        } else {
            //API 小于23 使用记录访问权限监测方式
            int permission = ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            return permission == PackageManager.PERMISSION_GRANTED;
        }
    }


    private boolean isPagerServiceRunning() {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if ("com.yuyang.wifi.service.LiveWallpaperService".equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
}
